﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace DeviceServer
{
    partial class HttpTool
    {
            private static HttpClient _client;
         

        static HttpTool()
        {
            _client = new HttpClient();
            _client.BaseAddress = new Uri(ConfigurationManager.AppSettings["ServerAddress"]);
            _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }


        public static async Task<T> GetAsync<T>(string url) where T : class
        {
            HttpResponseMessage response = await _client.GetAsync(url);
            if (response.IsSuccessStatusCode)
            {
                var data = await response.Content.ReadAsAsync<T>();
                return data;
            }
            else
            {

                // log.Error(string.Format("异步Get请求，url:{0}，调用失败，状态：{1},原因：{2}", url, response.StatusCode, response.ReasonPhrase));
                return null;
            }
        }

        public static async Task<T> PostAsJsonAsync<T>(string url, object entity) where T : class
        {
            HttpResponseMessage response = await _client.PostAsJsonAsync(url, entity);
            if (response.IsSuccessStatusCode)
            {
                var data = await response.Content.ReadAsAsync<T>();
                return data;
            }
            else
            {
                //log.Error(string.Format("异步Post请求，url:{0}，调用失败，状态：{1},原因：{2}", url, response.StatusCode, response.ReasonPhrase));
                return null;
            }
        }

        public static async Task<string> PostAsJsonAsync(string url, object entity)
        {
            HttpResponseMessage response = await _client.PostAsJsonAsync(url, entity);
            if (response.IsSuccessStatusCode)
            {
                var data = await response.Content.ReadAsStringAsync();
                return data;
            }
            else
            {
                //log.Error(string.Format("异步Post请求，url:{0}，调用失败，状态：{1},原因：{2}", url, response.StatusCode, response.ReasonPhrase));
                return null;
            }
        }
    }
}
